import Vue from "vue";
export default {
  //json参数转url
  urlCode(url, data) {
    let u = url;
    let n = 0;
    for (const param in data) {
      if (url.indexOf("?") < 0 && n == 0) {
        u += "?" + param + "=" + encodeURIComponent(data[param]);
      } else {
        u += "&" + param + "=" + encodeURIComponent(data[param]);
      }
      n++;
    }
    return u;
  },
  //格式化数字，用于页面输入限制
  formatFloat(ev, fixed = 2) {
    if (fixed == 0) {
      let reg = /^[0-9](\d+)?$/;
      if (!reg.test(ev.target.value)) {
        let reg2 = /^[0-9](\d+)?/;
        if (ev.target.value.match(reg2)) {
          ev.target.value = ev.target.value.match(reg2)[0];
        } else {
          ev.target.value = '';
        }
        ev.target._value = ev.target.value;
      }
      if (ev.target.value !== "") {
        return Number(ev.target.value);
      }
      return ev.target.value;
    } else {
      let reg = new RegExp("(^[1-9]([0-9]+)?(\\.[0-9]{1," + fixed + "})?$)|(^[0-9]\\.[0-9]([0-9]{0," + (fixed - 1) + "})?$)|(^(0){1}$)");
      let reg1 = new RegExp("^[0-9]+\\.{1}$");
      if (!reg.test(ev.target.value) && !reg1.test(ev.target.value)) {
        let reg2 = new RegExp("(^[1-9]([0-9]+)?(\\.[0-9]{1," + fixed + "})?)|(^[0-9]\\.[0-9]([0-9]{0," + (fixed - 1) + "})?)|(^(0){1})");
        if (ev.target.value.match(reg2)) {
          ev.target.value = ev.target.value.match(reg2)[0];
        } else {
          ev.target.value = '';
        }
        ev.target._value = ev.target.value;
      }
      return ev.target.value;
    }
  },
  //回退
  goBack() {
    window.history.length > 1 ? this.$router.go(-1) : this.$router.push('/');
  },
  //设置session
  removeSession(key) {
    sessionStorage.removeItem(key);
  },
  //设置session
  setSession(key, value) {
    if (value instanceof Object) {
      value = JSON.stringify(value);
    }
    sessionStorage.setItem(key, value);
  },
  //获取ession
  getSession(key) {
    let value = sessionStorage.getItem(key);
    try {
      return JSON.parse(value)
    } catch (e) {
      return value
    }
  },
  // 设置cookie信息
  setCookie(key, value) {
    var Days = 30;   //cookie 将被保存30天
    var exp = new Date();  //获得当前时间
    exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);  //换成毫秒
    document.cookie = key + "=" + JSON.stringify(value) + ";expires=" + exp.toGMTString();
    // if (value instanceof Object) {
    //   value = JSON.stringify(value);
    // }
    // localStorage.setItem(key, value);
  },
  // 删除cookie
  removeCookie(name) {
    this.setCookie(name, "");
    // localStorage.removeItem(name);
  },
  getEN(i) {
    return String.fromCharCode(i + 65);
  },
  // 获取cookie信息
  getCookie(key) {
    let cookieString = document.cookie;
    let arr = cookieString.split(';');
    let obj = {};
    for (let i = 0; i < arr.length; i++) {
      let a = arr[i].split('=');
      obj[a[0].trim()] = a[1];
    }
    try {
      return JSON.parse(obj[key])
    } catch (e) {
      return obj[key] || ''
    }
    // let value = localStorage.getItem(key);
    // try {
    //   return JSON.parse(value)
    // } catch (e) {
    //   return value
    // }
  },
  //消息弹框
  message(type = "error", message, duration = 2000, showClose = true) {
    Vue.prototype.$notify({
      showClose,
      message,
      title: "消息提示",
      type,
      duration,
      offset: 40,
      position: "top-left",
      // center: true,
    });
  },
  toast(type, message, duration = 2000, config = {}) {
    if (type == "clear") {
      Vue.prototype.$toast.clear();
    } else {
      Vue.prototype.$toast({
        type,
        message,
        duration: type == "loading" ? 0 : duration,
        forbidClick: type == "loading" ? true : (config.forbidClick || false),
        position: type == "text" ? "bottom" : "middle",
      });
    }
  },
  // 获取用户信息
  getUserInfo() {
    // const pathname = location.pathname.replace(/\//g, "") || "ms";
    // var userInfo = this.getSession("userInfo");
    // if (pathname == "mb") {
    //   userInfo = this.getCookie("userInfo");
    // }
    var userInfo = this.getSession("userInfo") || this.getCookie("userInfo");
    if (typeof userInfo != 'object') {
      userInfo = {};
    }
    return userInfo;
  },
  //获取token
  getToken() {
    var userInfo = this.getUserInfo();
    if (userInfo && userInfo.token) {
      return (userInfo.token_type || "Bearer") + " " + userInfo.token
    }
    return "";
  },
  getTimestamp(date) {
    var time = this.formatDate(date, "yyyy/MM/dd HH:mm:ss");
    return new Date(time).getTime();
  },
  getNextDays(date, num, format) {
    var timestamp = this.getTimestamp(date) + num * 24 * 60 * 60 * 1000;
    return this.formatDate(timestamp, format);
  },
  getCutTime(type, times) {
    var h = parseInt(times / 60 / 60 % 24); //时
    h = h < 10 ? '0' + h : h;
    var m = parseInt(times / 60 % 60);
    m = m < 10 ? '0' + m : m;
    var s = parseInt(times % 60);
    s = s < 10 ? '0' + s : s;
    var cutTime = h + ":" + m + ":" + s;
    if (type == "m") {
      m = parseInt(m) + parseInt(h) * 60;
      m = m < 10 ? '0' + m : m;
      cutTime = m + ":" + s;
    }
    return cutTime;
  },
  //时间格式化
  formatDate(date, format, isMoment) {
    if (!date) return "";
    if (!format) format = "yyyy-MM-dd HH:mm:ss";
    var tagNum = /^[0-9]*$/.test(date);
    date = date + "";
    if (!tagNum && date.indexOf("T") < 0) {
      date = date.replace(/-/g, "/");
    }
    if (tagNum || Date.parse(date)) {
      if (tagNum) date = parseInt(date);
      date = new Date(date).getTime();
      if (date.toString().length == 10) {
        date = date * 1000;
      }
      let offest = new Date().getTimezoneOffset();
      if (isMoment) date = date - offest * 1000 * 60;
      let datetime = dateFtt(format, date);
      return datetime;
    } else {
      return date;
    }
    /**************************************时间格式化处理************************************/
    function dateFtt(fmt, date) { //author: meizz   
      var date = new Date(date);
      var o = {
        "M+": date.getMonth() + 1, //月份   
        "d+": date.getDate(), //日   
        "H+": date.getHours(), //小时   
        "m+": date.getMinutes(), //分   
        "s+": date.getSeconds(), //秒   
        "q+": Math.floor((date.getMonth() + 3) / 3), //季度   
        "S": date.getMilliseconds() //毫秒   
      };
      if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
      for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
          fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
      return fmt;
    }
  },
  base64() {
    // private property
    var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    // public method for encoding
    this.encode = function (input) {
      var output = "";
      var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
      var i = 0;
      input = _utf8_encode(input);
      while (i < input.length) {
        chr1 = input.charCodeAt(i++);
        chr2 = input.charCodeAt(i++);
        chr3 = input.charCodeAt(i++);
        enc1 = chr1 >> 2;
        enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
        enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
        enc4 = chr3 & 63;
        if (isNaN(chr2)) {
          enc3 = enc4 = 64;
        } else if (isNaN(chr3)) {
          enc4 = 64;
        }
        output = output +
          _keyStr.charAt(enc1) + _keyStr.charAt(enc2) +
          _keyStr.charAt(enc3) + _keyStr.charAt(enc4);
      }
      return output;
    }
    // public method for decoding
    this.decode = function (input) {
      var output = "";
      var chr1, chr2, chr3;
      var enc1, enc2, enc3, enc4;
      var i = 0;
      input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
      while (i < input.length) {
        enc1 = _keyStr.indexOf(input.charAt(i++));
        enc2 = _keyStr.indexOf(input.charAt(i++));
        enc3 = _keyStr.indexOf(input.charAt(i++));
        enc4 = _keyStr.indexOf(input.charAt(i++));
        chr1 = (enc1 << 2) | (enc2 >> 4);
        chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
        chr3 = ((enc3 & 3) << 6) | enc4;
        output = output + String.fromCharCode(chr1);
        if (enc3 != 64) {
          output = output + String.fromCharCode(chr2);
        }
        if (enc4 != 64) {
          output = output + String.fromCharCode(chr3);
        }
      }
      output = _utf8_decode(output);
      return output;
    }

    // private method for UTF-8 encoding
    var _utf8_encode = function (string) {
      string = string.replace(/\r\n/g, "\n");
      var utftext = "";
      for (var n = 0; n < string.length; n++) {
        var c = string.charCodeAt(n);
        if (c < 128) {
          utftext += String.fromCharCode(c);
        } else if ((c > 127) && (c < 2048)) {
          utftext += String.fromCharCode((c >> 6) | 192);
          utftext += String.fromCharCode((c & 63) | 128);
        } else {
          utftext += String.fromCharCode((c >> 12) | 224);
          utftext += String.fromCharCode(((c >> 6) & 63) | 128);
          utftext += String.fromCharCode((c & 63) | 128);
        }

      }
      return utftext;
    }

    // private method for UTF-8 decoding
    var _utf8_decode = function (utftext) {
      var string = "";
      var i = 0;
      var c = c1 = c2 = 0;
      while (i < utftext.length) {
        c = utftext.charCodeAt(i);
        if (c < 128) {
          string += String.fromCharCode(c);
          i++;
        } else if ((c > 191) && (c < 224)) {
          c2 = utftext.charCodeAt(i + 1);
          string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
          i += 2;
        } else {
          c2 = utftext.charCodeAt(i + 1);
          c3 = utftext.charCodeAt(i + 2);
          string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
          i += 3;
        }
      }
      return string;
    }
  },
  //url到处文件
  exportExcel(url, target = '') {
    const alink = document.createElement('a');
    alink.style.display = 'none';
    alink.setAttribute("target", target);
    alink.href = url;
    document.body.appendChild(alink);
    alink.click();
    document.body.removeChild(alink);
  },
  //文件流下载
  fileDownload(data, excelName) {
    const blob = new Blob([data], { type: 'application/octet-stream' })
    const alink = document.createElement('a');
    alink.download = `${excelName}`;
    alink.href = URL.createObjectURL(blob);
    alink.click();
  },
  //去左右空格;
  trim(s) {
    return s.replace(/(^\s*)|(\s*$)/g, "");
  },
  //十六进制颜色转RGB
  hex2rgb(color) {
    if (!color) return false;
    color = color.substring(1);
    color = color.toLowerCase();
    let b = [];
    for (let x = 0; x < 3; x++) {
      b[0] = color.substr(x * 2, 2);
      b[3] = "0123456789abcdef";
      b[1] = b[0].substr(0, 1);
      b[2] = b[0].substr(1, 1);
      b[20 + x] = b[3].indexOf(b[1]) * 16 + b[3].indexOf(b[2]);
    }
    // console.log([b[20],b[21],b[22]])
    return [b[20], b[21], b[22]];
    // return "rgb(" +b[20]+","+b[21]+","+b[22]+ ")";
  },
  //保留小数点，只舍不入
  retainDecimal(num, fixed) {
    num = num + "";
    if (num.indexOf(".") < 0) {
      return num;
    }
    return num.substring(0, num.lastIndexOf('.') + (fixed + 1));
  },
  //深拷贝
  depCopy(obj) {
    try {
      return JSON.parse(JSON.stringify(obj))
    } catch (e) {
      return obj
    }
  },
  uuid(len, radix) {
    var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
    var uuid = [], i;
    radix = radix || chars.length;
    if (len) {
      for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
    } else {
      var r;
      uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
      uuid[14] = '4';
      for (i = 0; i < 36; i++) {
        if (!uuid[i]) {
          r = 0 | Math.random() * 16;
          uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
        }
      }
    }
    return uuid.join('');
  },
  parseQueryString(type) {
    var url = location.search;
    if (type === 'hash') {
      url = location.hash.substring(location.hash.indexOf("?"));
    }
    var query = {};
    if (url.indexOf("?") !== -1) {
      var str = url.substr(1);
      var strs = str.split("&");
      for (var i = 0; i < strs.length; i++) {
        query[strs[i].split("=")[0]] = decodeURIComponent(strs[i].split("=")[1]);
      }
    }
    return query;
  },
  fileView(path, server) {
    if (!path) {
      return "";
    }
    if (server == "own") {
      return 'http://47.115.75.110:8012/onlinePreview?url=' + Base64.encode(path);
    } else {
      let target = ['.doc', '.xls', '.ppt'].find(item => path.indexOf(item) > 0);
      if (target) {
        return "https://view.officeapps.live.com/op/view.aspx?src=" + encodeURIComponent(path);
      } else {
        return path;
      }
    }
  },
  platform(value) {
    var platform = "";
    switch (value) {
      case "ms": platform = "管理端"; break;
      case "pc": platform = "客户端"; break;
      case "mb": platform = "手机端"; break;
      default: platform = "其他";
    }
    return platform;
  },
  imageResize(url, w, h) {
    return `${url}?x-oss-process=image/resize,w_${w},h_${h}`
  },
  random(min, max) {
    return Math.floor(Math.random() * (max - min)) + min
  },
  getDateDays(date, cycle) {
    var obj = {
      date: date,
      // cycle,
      total: this.getDaysBetween(cycle.cycleStartTime, cycle.cycleEndTime),
      days: this.getDaysBetween(cycle.cycleStartTime, date),
    };
    obj.percent = Number((obj.days / obj.total * 100).toFixed(2));
    if (obj.percent < 0) {
      obj.percent = 0;
    }
    if (obj.percent > 100) {
      obj.percent = 100;
    }
    return obj;
  },
  getDaysInMonth(year, month) {
    let date = new Date(year, month, 1);
    return new Date(date.getTime() - 864e5).getDate();
  },
  getYearDays(year) {
    year = year || new Date().getFullYear();
    var isLeap = year % 4 == 0 && year % 100 != 0 || year % 400 == 0;
    return isLeap ? 366 : 365;
  },
  getDaysBetween(start, end) {
    var startDate = Date.parse(start);
    var endDate = Date.parse(end);
    if (startDate > endDate) {
      return 0;
    }
    // if (startDate==endDate){
    //     return 1;
    // }
    var days = (endDate - startDate) / (1 * 24 * 60 * 60 * 1000);
    return days;
  },
  fullScreen() {
    this.requestFullscreenFunName = null;
    this.exitFullscreenFunName = null;
    this.supprotFullScreen = false;
    let body = document.body;
    if (typeof body.requestFullscreen === 'function') {
      this.requestFullscreenFunName = 'requestFullscreen';
    } else if (typeof body.mozRequestFullScreen === 'function') {
      this.requestFullscreenFunName = 'mozRequestFullScreen';
    } else if (typeof body.msRequestFullscreen === 'function') {
      this.requestFullscreenFunName = 'msRequestFullscreen';
    } else if (typeof body.oRequestFullscreen === 'function') {
      this.requestFullscreenFunName = 'oRequestFullscreen';
    } else if (typeof body.webkitRequestFullscreen === 'function') {
      this.requestFullscreenFunName = 'webkitRequestFullscreen';
    }

    if (typeof document.exitFullscreen === 'function') {
      this.exitFullscreenFunName = 'exitFullscreen';
    } else if (typeof document.msExitFullscreen === 'function') {
      this.exitFullscreenFunName = 'msExitFullscreen';
    } else if (typeof document.mozCancelFullScreen === 'function') {
      this.exitFullscreenFunName = 'mozCancelFullScreen';
    } else if (typeof document.oRequestFullscreen === 'function') {
      this.exitFullscreenFunName = 'oRequestFullscreen';
    } else if (typeof document.webkitExitFullscreen === 'function') {
      this.exitFullscreenFunName = 'webkitExitFullscreen';
    }
    this.supprotFullScreen = (null !== this.requestFullscreenFunName && null !== this.exitFullscreenFunName);
    // 进入全屏
    this.enterFullscreen = function (element) {
      if (!this.supprotFullScreen) {
        return;
      }
      element[this.requestFullscreenFunName]();
    };
    // 退出全屏
    this.exitFullscreen = function () {
      if (!this.supprotFullScreen) {
        return;
      }
      document[this.exitFullscreenFunName]();
    }
  },
  stopMedia() {
    var timer = setTimeout(() => {
      var videos = document.getElementsByTagName("video");
      for (var i = 0; i < videos.length; i++) {
        videos[i].pause();
      }
      var audios = document.getElementsByTagName("audio");
      for (var i = 0; i < audios.length; i++) {
        audios[i].pause();
      }
      clearTimeout(timer);
    })
  },
  hexToRgba(hex, opacity) {
    return 'rgba(' + parseInt('0x' + hex.slice(1, 3)) + ',' + parseInt('0x' + hex.slice(3, 5)) + ',' + parseInt('0x' + hex.slice(5, 7)) + ',' + opacity + ')'
  },
  getRandomArrayElements(arr, count) {
    if (count > arr.length) {
      count = arr.length;
    }
    var shuffled = arr.slice(0), i = arr.length, min = i - count, temp, index;
    while (i-- > min) {
      index = Math.floor((i + 1) * Math.random());
      temp = shuffled[index];
      shuffled[index] = shuffled[i];
      shuffled[i] = temp;
    }
    return shuffled.slice(min);
  },
  chartSize(val) {
    let clientWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
    if (!clientWidth) return;
    let percent = clientWidth / 1920;
    return val * percent;
  }
}
